import React, { useState, useEffect } from 'react';
import { Table, Input, Button, Space, Tag, Popconfirm, message, Modal, Form, Select, DatePicker } from 'antd';
import { SearchOutlined, DownloadOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';

const { Column, ColumnGroup } = Table;
const { Option } = Select;
const { RangePicker } = DatePicker;

const DownloadPage = () => {
    const [dataSource, setDataSource] = useState([]);
    const [loading, setLoading] = useState(false);
    const [searchText, setSearchText] = useState('');
    const [visible, setVisible] = useState(false);
    const [form] = Form.useForm();

    useEffect(() => {
        fetchData();
    }, []);

    const fetchData = async () => {
        setLoading(true);
        try {
            // 模拟API请求
            // const response = await axios.get('https://api.example.com/downloads');
            // setDataSource(response.data);
        } catch (error) {
            message.error('获取下载数据失败');
        } finally {
            setLoading(false);
        }
    };

    const handleSearch = (value) => {
        setSearchText(value);
        // 实际项目中这里应该调用API进行搜索
        const filteredData = dataSource.filter(item =>
            item.name.includes(value) || item.category.includes(value)
        );
        setDataSource(filteredData);
    };

    const handleDelete = async (record) => {
        try {
            // 模拟API请求
            await axios.delete(`https://api.example.com/downloads/${record.id}`);
            message.success('删除成功');
            fetchData();
        } catch (error) {
            message.error('删除失败');
        }
    };

    const handleDownload = (record) => {
        // 实际项目中这里应该触发下载逻辑
        message.info(`开始下载: ${record.name}`);
    };

    const showModal = () => {
        setVisible(true);
    };

    const handleOk = () => {
        form.validateFields()
            .then(values => {
                form.resetFields();
                setVisible(false);
                // 实际项目中这里应该调用API添加下载
                message.success('添加下载成功');
                fetchData();
            })
            .catch(info => {
                console.log('Validate Failed:', info);
            });
    };

    const handleCancel = () => {
        form.resetFields();
        setVisible(false);
    };

    return (
        <div className="download-page">
            <div className="download-header">
                <h2 className="download-title">下载管理</h2>
                <Space>
                    <Input.Search
                        placeholder="搜索资源名称或分类"
                        onSearch={handleSearch}
                        enterButton={<SearchOutlined />}
                        className="search-input"
                    />
                    <Button type="primary" icon={<PlusOutlined />} onClick={showModal}>
                        添加下载
                    </Button>
                </Space>
            </div>

            <Table
                dataSource={dataSource}
                loading={loading}
                pagination={{ pageSize: 10 }}
                rowKey="id"
            >
                <Column
                    title="名称"
                    dataIndex="name"
                    key="name"
                    render={(text, record) => (
                        <a href="#" onClick={() => handleDownload(record)}>{text}</a>
                    )}
                />
                <ColumnGroup title="信息">
                    <Column
                        title="分类"
                        dataIndex="category"
                        key="category"
                        render={(text) => (
                            <Tag color="blue">{text}</Tag>
                        )}
                    />
                    <Column
                        title="大小"
                        dataIndex="size"
                        key="size"
                    />
                </ColumnGroup>
                <Column
                    title="状态"
                    dataIndex="status"
                    key="status"
                    render={(text) => {
                        let color = 'green';
                        if (text === '暂停') color = 'orange';
                        if (text === '失败') color = 'red';
                        return <Tag color={color}>{text}</Tag>;
                    }}
                />
                <Column
                    title="进度"
                    dataIndex="progress"
                    key="progress"
                    render={(text) => (
                        <div className="progress-bar" style={{ width: '100%' }}>
                            <div className="progress-value" style={{ width: `${text}%` }}></div>
                            <span className="progress-text">{text}%</span>
                        </div>
                    )}
                />
                <Column
                    title="操作"
                    key="action"
                    render={(text, record) => (
                        <Space size="middle">
                            <Button
                                type="primary"
                                size="small"
                                icon={<DownloadOutlined />}
                                onClick={() => handleDownload(record)}
                            >
                                下载
                            </Button>
                            <Popconfirm
                                title="确定要删除吗?"
                                onConfirm={() => handleDelete(record)}
                                okText="确定"
                                cancelText="取消"
                            >
                                <Button type="danger" size="small" icon={<DeleteOutlined />}>
                                    删除
                                </Button>
                            </Popconfirm>
                        </Space>
                    )}
                />
            </Table>

            <Modal
                title="添加新下载"
                visible={visible}
                onOk={handleOk}
                onCancel={handleCancel}
                okText="确定"
                cancelText="取消"
            >
                <Form
                    form={form}
                    name="download_form"
                    layout="vertical"
                    initialValues={{ remember: true }}
                >
                    <Form.Item
                        name="url"
                        label="种子URL"
                        rules={[{ required: true, message: '请输入种子URL' }]}
                    >
                        <Input placeholder="请输入种子URL" />
                    </Form.Item>
                    <Form.Item
                        name="category"
                        label="分类"
                        rules={[{ required: true, message: '请选择分类' }]}
                    >
                        <Select placeholder="请选择分类">
                            <Option value="movie">电影</Option>
                            <Option value="tv">剧集</Option>
                            <Option value="music">音乐</Option>
                            <Option value="game">游戏</Option>
                            <Option value="software">软件</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="downloadPath"
                        label="下载路径"
                        rules={[{ required: true, message: '请选择下载路径' }]}
                    >
                        <Select placeholder="请选择下载路径">
                            <Option value="/mnt/downloads/movies">/mnt/downloads/movies</Option>
                            <Option value="/mnt/downloads/tv">/mnt/downloads/tv</Option>
                            <Option value="/mnt/downloads/music">/mnt/downloads/music</Option>
                            <Option value="/mnt/downloads/other">/mnt/downloads/other</Option>
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="dateRange"
                        label="有效期"
                    >
                        <RangePicker showTime format="YYYY-MM-DD HH:mm:ss" />
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default DownloadPage;